package com.xzq.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xzq.erp.context.BaseContext;
import com.xzq.erp.domain.po.SysPermission;
import com.xzq.erp.domain.po.SysRole;
import com.xzq.erp.domain.po.SysUser;
import com.xzq.erp.mapper.SysPermissionMapper;
import com.xzq.erp.mapper.SysRoleMapper;
import com.xzq.erp.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户详情服务实现类
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserMapper userMapper;
    private final SysRoleMapper roleMapper;
    private final SysPermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        log.info("加载用户ID: {}", userId);
        
        // 查询用户
        SysUser user = userMapper.selectOne(
            new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getId, Integer.valueOf(userId))
        );
        
        if (user == null) {
            log.error("用户不存在: {}", userId);
            throw new UsernameNotFoundException("用户不存在: " + userId);
        }
        
        if (!user.getStatus()) {
            log.error("用户已禁用: {}", userId);
            throw new UsernameNotFoundException("用户已禁用: " + userId);
        }
        //  设置当前用户ID
        BaseContext.setUserId(Long.valueOf(user.getId()));
        
        // 获取用户角色和权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        
        // 查询用户角色
        List<SysRole> roles = roleMapper.selectRolesByUserId(user.getId());
        
        // 添加ROLE_前缀的角色权限
        List<String> roleNames = roles.stream()
            .filter(r -> r.getStatus() == 1)  // 只取启用的角色
            .map(role -> "ROLE_" + role.getName())
            .collect(Collectors.toList());
        // ROLE_开头为角色
        roleNames.forEach(roleName -> authorities.add(new SimpleGrantedAuthority(roleName)));
        
        // 查询用户权限
        List<SysPermission> permissions = permissionMapper.selectPermissionsByUserId(user.getId());
        
        // 添加权限标识符
        List<String> permissionNames = permissions.stream()
            .map(SysPermission::getName)
            .collect(Collectors.toList());
        
        permissionNames.forEach(permissionName -> authorities.add(new SimpleGrantedAuthority(permissionName)));
        
        log.info("用户 {} 的角色和权限: {}", userId, authorities);
        
        return new User(user.getUsername(), user.getPassword(), authorities);
    }
} 